<template>
    <div class="provider-audit-manage">
      <!-- 查询区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
        <el-form-item label="供应商名称">
          <el-input v-model="searchForm.providerName" placeholder="请输入供应商名称" clearable />
        </el-form-item>
        <el-form-item label="企业类型">
          <el-select v-model="searchForm.companyType" placeholder="请选择企业类型" clearable>
            <el-option label="国有企业" value="国有企业" />
            <el-option label="民营企业" value="民营企业" />
            <el-option label="外资企业" value="外资企业" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
            <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" clearable>
                <el-option label="未审核" :value="0" />
                <el-option label="未通过" :value="2" />
            </el-select>
        </el-form-item>
        <el-form-item label="成立年份">
          <el-date-picker
            v-model="searchForm.establishedYearRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始年份"
            end-placeholder="结束年份"
            value-format="YYYY"
            :picker-options="{type: 'year'}"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="showAddDialog = true">添加供应商</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 供应商列表 -->
      <el-table :data="providerList" border>
        <el-table-column prop="providerId" label="供应商编号" min-width="100" />
        <el-table-column prop="providerName" label="供应商名称" min-width="120" />
        <el-table-column prop="factoryAddress" label="厂址" min-width="150" />
        <el-table-column prop="principalName" label="负责人姓名" min-width="100" />
        <el-table-column prop="principalPhone" label="负责人联系电话" min-width="120">
          <template #default="{ row }">{{ row.principalPhone || '-' }}</template>
        </el-table-column>
        <el-table-column prop="companyType" label="企业类型" min-width="100" />
        <el-table-column prop="registeredCapital" label="注册资本" min-width="100" />
        <el-table-column prop="employeeCount" label="员工人数" min-width="100" />
        <el-table-column prop="establishedYear" label="成立年份" min-width="100" />
        <el-table-column prop="auditStatus" label="审核状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="statusType[row.auditStatus]">
              {{ statusMap[row.auditStatus] || '未审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" :min-width="isAdmin ? 240 : 145">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEditProvider(row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDeleteProvider(row.providerId)">删除</el-button>
            <el-button 
              v-if="row.auditStatus === 0 && isAdmin" 
              size="small" 
              type="success" 
              @click="handleAudit(row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="pagination.total"
        :page-size="pagination.size"
        :current-page="pagination.current"
        @current-change="handlePageChange"
      />
  
      <!-- 添加/修改供应商对话框 -->
      <el-dialog :title="editProviderId ? '修改供应商' : '添加供应商'" v-model="showAddDialog">
        <el-form :model="addForm" label-width="100px" :rules="formRules">
          <el-form-item label="供应商名称" prop="providerName">
            <el-input v-model="addForm.providerName" />
          </el-form-item>
          <el-form-item label="厂址" prop="factoryAddress">
            <el-input v-model="addForm.factoryAddress" />
          </el-form-item>
          <el-form-item label="负责人姓名" prop="principalName">
            <el-input v-model="addForm.principalName" />
          </el-form-item>
          <el-form-item label="负责人电话" prop="principalPhone">
            <el-input v-model="addForm.principalPhone" placeholder="请输入11位手机号" />
          </el-form-item>
          <el-form-item label="企业类型" prop="companyType">
            <el-select v-model="addForm.companyType" placeholder="请选择企业类型">
              <el-option label="国有企业" value="国有企业" />
              <el-option label="民营企业" value="民营企业" />
              <el-option label="外资企业" value="外资企业" />
            </el-select>
          </el-form-item>
          <el-form-item label="注册资本" prop="registeredCapital">
            <el-input v-model="addForm.registeredCapital" type="number" />
          </el-form-item>
          <el-form-item label="员工人数" prop="employeeCount">
            <el-input v-model="addForm.employeeCount" type="number" />
          </el-form-item>
          <el-form-item label="成立年份" prop="establishedYear">
            <el-date-picker 
              v-model="addForm.establishedYear" 
              type="year" 
              placeholder="选择年份" 
              value-format="YYYY"
              style="width: 100%;" 
            />
          </el-form-item>
          <el-form-item label="简介" prop="description">
            <el-input v-model="addForm.description" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAddDialog = false; editProviderId = null">取消</el-button>
          <el-button type="primary" @click="handleSubmitProvider">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 审核对话框 -->
      <el-dialog title="供应商审核" v-model="showAuditDialog">
        <el-form :model="auditForm" label-width="100px">
          <el-form-item label="供应商名称">
            <span>{{ currentProvider?.providerName }}</span>
          </el-form-item>
          <el-form-item label="审核结果" prop="auditStatus">
            <el-radio-group v-model="auditForm.auditStatus">
              <el-radio :value="1">通过</el-radio>
              <el-radio :value="2">不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见" prop="auditComment">
            <el-input 
              v-model="auditForm.auditComment" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入审核意见"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAuditDialog = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios';
  import { useUserStore } from '@/stores/user'
  
  // 状态映射
  const statusMap = {
    0: '未审核',
    1: '已通过',
    2: '未通过'
  }
  
  const statusType = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  
  // 从Pinia获取用户信息
const userStore = useUserStore()
  // 权限控制
  const userTitle = computed(() => userStore.userInfo?.title || '普通操作人员')
  const isAdmin = computed(() => ['部门经理'].includes(userTitle.value))
  const currentUser = computed(() => userStore.userInfo)
  
  const searchForm = reactive({
    providerName: '',
    companyType: '',
    auditStatus: null,
    establishedYearRange: [],
  })
  
  const addForm = reactive({
    providerName: '',
    factoryAddress: '',
    principalName: '',
    principalPhone: '',
    companyType: '',
    registeredCapital: '',
    employeeCount: '',
    establishedYear: '',
    description: ''
  })
  
  const formRules = reactive({
    providerName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
    companyType: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
    principalPhone: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  })
  
  const providerList = ref([])
  const pagination = reactive({
    total: 0,
    size: 10,
    current: 1
  })
  const showAddDialog = ref(false)
  const editProviderId = ref<number | null>(null)
  
  // 审核相关
  const showAuditDialog = ref(false)
  const currentProvider = ref(null)
  const auditForm = reactive({
    providerId: null,
    auditStatus: 1,
    auditComment: '',
    auditorId: computed(() => currentUser.value?.id || null) // 从当前登录用户获取ID
  })
  
  const handleAudit = (row) => {
    currentProvider.value = row
    auditForm.providerId = row.providerId
    auditForm.auditStatus = 1
    auditForm.auditComment = ''
    showAuditDialog.value = true
  }
  
  const submitAudit = async () => {
    try {
      const params = new URLSearchParams()
      params.append('providerId', auditForm.providerId)
      params.append('auditStatus', auditForm.auditStatus)
      params.append('auditComment', auditForm.auditComment)
      params.append('auditorId', auditForm.auditorId)

/*       const params = {
        'providerId': auditForm.providerId,
        'auditStatus': auditForm.auditStatus,
        'auditComment': auditForm.auditComment,
        'auditorId': auditForm.auditorId
      } */
      
      
      console.log(111);
      
      console.log(params);
      
      await axios.post(
        import.meta.env.VITE_API_URL + 'provider/audit',
        params
      )
      
      ElMessage.success('审核成功')
      showAuditDialog.value = false
      fetchProviders(pagination.current)
    } catch (e) {
      ElMessage.error('审核失败')
    }
  }
  
  const fetchProviders = async (pageNum = 1) => {
    try {
        const params = {
            providerName: searchForm.providerName || null,
            companyType: searchForm.companyType || null,
            auditStatus: searchForm.auditStatus || 0, // 默认显示未审核的供应商
            establishedYearBegin: searchForm.establishedYearRange?.[0] || null,
            establishedYearEnd: searchForm.establishedYearRange?.[1] || null
        }
        const res = await axios.post(
        import.meta.env.VITE_API_URL + `provider/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
        params
        )
        providerList.value = res.data.records
        pagination.total = res.data.total
        pagination.current = res.data.current
        pagination.size = res.data.size
    } catch (e) {
        ElMessage.error('获取供应商数据失败')
    }
}
  
  const handleEditProvider = (row: any) => {
    Object.assign(addForm, row)
    editProviderId.value = row.providerId
    showAddDialog.value = true
  }
  
  const handleDeleteProvider = async (providerId: number) => {
    try {
      await axios.delete(import.meta.env.VITE_API_URL + `provider/${providerId}`)
      ElMessage.success('删除成功')
      fetchProviders(1)
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }
  
  const handleSubmitProvider = async () => {
    try {
      const url = editProviderId.value 
        ? import.meta.env.VITE_API_URL + 'provider/update'
        : import.meta.env.VITE_API_URL + 'provider/save'
  
      await axios.post(url, {
        ...addForm,
        providerId: editProviderId.value
      })
  
      ElMessage.success(editProviderId.value ? '修改成功' : '添加成功')
      showAddDialog.value = false
      editProviderId.value = null
      await fetchProviders(1)
    } catch (e) {
      ElMessage.error(editProviderId.value ? '修改失败' : '添加失败')
    }
  }
  
  const handleSearch = () => fetchProviders(1)
  const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
      if (Array.isArray(searchForm[key])) {
        searchForm[key] = []
      } else {
        searchForm[key] = null
      }
    })
    fetchProviders(1)
  }
  const handlePageChange = (page: number) => fetchProviders(page)
  
  onMounted(() => {
    fetchProviders(1)
  })
  </script>
  
  <style scoped>
  @import '@/styles/views.css';
  </style>